<?php
/**
 * Instead of putting each step on a separate page, each step will post back to this page and be
 * processed in the next step if it passes the previous step.
 */
 
define("ROOTDIR", dirname(__FILE__)); // Global Constant of root directory

require_once(ROOTDIR."/include/database/class.InstallAndUpgradeQueries.php");

session_start();

$installAndUpgrade = new InstallAndUpgradeQueries();

// The step of the install process
$step = 1;
if(isset($_POST['step'])) {
  $step = $_POST['step'];
}

/*************************************************
 * Validate step data
 *************************************************/
// Step 1 has been processed
if($step == 2) {
  // Determine if we can really continue to step 2
  // Check to see if the database user and password are correct
  $installAndUpgrade->setDbHost($_POST['dbhost']);
  $installAndUpgrade->setDbUser($_POST['dbuser']);
  $installAndUpgrade->setDbPass($_POST['dbpass']);
  
  // Store the values into the session so that they can be grabbed on the next page
  $_SESSION['dbhost'] = $_POST['dbhost'];
  $_SESSION['dbuser'] = $_POST['dbuser'];
  $_SESSION['dbpass'] = $_POST['dbpass'];
  
  // If the test fails, they will told and will have to click the back button to correct it
  $installAndUpgrade->testConnection();
}
// Step 2 has been processed
if($step == 3) {
  $newOrExisting = $_POST['newOrExisting']; // 'New' or 'Existing'
  
  $installAndUpgrade->setDbHost($_SESSION['dbhost']);
  $installAndUpgrade->setDbUser($_SESSION['dbuser']);
  $installAndUpgrade->setDbPass($_SESSION['dbpass']);

  $installAndUpgrade->createConnection();
  
  $dbToUse = "";

  if($newOrExisting == "New") {
    // Create the database
    $dbToUse = $_POST['dbnameinput'];
    $installAndUpgrade->setDbase($dbToUse);
    $installAndUpgrade->createDatabase();
  } else {
    $dbToUse = $_POST['dbnameselect'];
    $installAndUpgrade->setDbase($dbToUse);
  }
  
  // Now connect to the database (new or existing)
  $installAndUpgrade->connectToDatabase();
  
  // Now create all the tables
  $installAndUpgrade->fullInstall();
  
  // Create config file
  $fh = fopen("config/class.Config.php", 'w');
  
  $logo = $_POST['logo'];
  
  if($logo == "") {
    $logo = "logo.png";
  }
  
  $emailCount = $_POST['emailCount']-1;
  $emailList = "";
  
  // Generate the list of Ban Manager Emails
  for($i=0; $i<$emailCount; $i++) {
    $inputName = "email".($i+1);
    $email = $_POST[$inputName];
    if(!empty($email)) {
      $emailList .= "\"".$email."\"";
      if($i < $emailCount-1) {
        $emailList .= ", ";
      }
    }
  }
  
  // Generate the php config file
  $configData = "<?php
/**
 *  This makes it easier to include configuration variables to other classes
 *  by simply extending the class with the Config class.  Any new variables that
 *  get added MUST have a getter as that will be the only way to retrieve a Config
 *  value if the config value needs to be used outside as it's own object.
 *
 *  Change ALL values below to what you desire for your website.  If you did not
 *  change the gban.sql file, then the database name will be global_ban.  Otherwise
 *  all other variables, espeically those in the database block should be changed
 *  appropriately.
 */

class Config {
  /**
   * Site specific settings
   */
  var $"."bansPerPage = ".$_POST['bansPerPage']."; // Number of bans to display on ban list page for each page (-1 show all)
  var $"."maxPageLinks = ".$_POST['numPageLinks']."; // Number of links to show before and after selected page (IE: set at 2 you would see 1 2 ... 10 11 [12] 13 14 ... 23 24)
  var $"."demoRootDir = \"".$_POST['demoDir']."\"; // Folder to save demos to (folder must be relative to banned dir)
  var $"."demoSizeLimit = \"".$_POST['demoSizeLimit']."\"; // Demo size limit in MB
  var $"."siteName = \"".$_POST['siteName']."\"; // The name of your website
  var $"."siteUrl = \"".$_POST['siteURL']."\"; // Your clan/server's home page
  var $"."siteLogo = \"".$logo."\"; // Found in images directory; you must save your logo to the images dir!!

  /**
   * SMF integration settings
   * The gban tables MUST be installed in your SMF database ($"."dbName = \"YOUR_SMF_DB\")
   * Full power admins are those with FULL ADMIN rights to the SMF boards
   * If you wish to use SMF integration you MUST install the zip under your Forums directory
   * So you will access the pages by going to Forums/banned
   */
  var $"."enableSmfIntegartion = ".$_POST['smfIntegration'].";  // Whether to enable SMF integartion
  var $"."memberGroup = ".$_POST['smfMemberGroup']."; // The SMF group id that contains all your members
  var $"."adminGroup = ".$_POST['smfAdminGroup']."; // The SMF group id that contains all your admins
  var $"."banManagerGroup = ".$_POST['smfBanManagerGroup']."; // The SMF group id that contains all your ban managers
  var $"."fullPowerGroup = ".$_POST['smfFullPowerGroup']."; // The SMF group id that is allowed full access to the GlobalBan site and admin tools

  /**
   * Ban specific settings
   */
  var $"."banMessage = \"".$_POST['banMessage']."\"; // Message to display to those banned
  var $"."appealSite = \"".$_POST['banAppealSite']."\"; // Site where user's should appeal a ban
  var $"."daysBanPending = ".$_POST['daysBanPending']."; // Number of days to keep someone with a \"pending\" ban off the server (0 to let the person come back after being \"banned\"); this only affects \"members\" who do bans longer than 1 day
  var $"."allowAdminBans = ".$_POST['allowAdminBan']."; // Set to true to allow the banning of admins (Default off - false)
  //var $"."numDemosToBan = -1; // The person uploading a demo needs to have X number of people banned from his demos before future uploads will auto-ban. (-1 is off)

  /**
   * Forum Settings
   * Very simple forum integration (Just adds a link button)
   */
  var $"."enableForumLink = ".$_POST['enableForumLink'].";
  var $"."forumURL = \"".$_POST['forumURL']."\"; // Link to your forums

  /**
   * Database Block
   */
  var $"."dbName = \"".$dbToUse."\"; // Set the Database to access (where all gban tables are located, change if you place your gban tables in a different db)
  var $"."dbUserName = \"".$_SESSION['dbuser']."\"; // Set the Database's user name login (recommend a user with only select, insert, update, and delete privs)
  var $"."dbPassword = \"".$_SESSION['dbpass']."\"; // Set the Database user's password login
  var $"."dbHostName = \"".$_SESSION['dbhost']."\"; // Set the Database's host
  var $"."matchHash = \"".$_POST['hash']."\"; // This must match the has found in the ES script (prevent's people from accessing the page outside)
  var $"."createUserCode = \"".$_POST['createUserCode']."\"; // This code must be entered for someone to create a new basic user
  var $"."createSuperCode = \"".$_POST['createSuperUserCode']."\"; // This code must be entered for someone to create a FULL power user

  /**
   *  Email address of those who should get notices of when a new ban has been added
   *  or changed.
   */
  var $"."sendEmails = ".$_POST['sendEmailsOnBan']."; // Send an email whenever a ban is added or updated (does not include imports)
  var $"."sendDemoEmails = ".$_POST['sendEmailsDemo']."; // Send an email whenever a new demo is added
  var $"."emailFromHeader = \"".$_POST['senderEmail']."\"; // The from email address
  var $"."banManagerEmails = array(".$emailList."); // Who recieves emails when new bans are added

  function __construct() {
  }

  function Config() {
  }
}
?".">
";
  
  fwrite($fh, $configData);
  fclose($fh);
}
?>


<?php
/*************************************************
 * STEP 1 - THE FIRST PAGE
 * GET THE DATABASE USER AND PASSWORD
 *************************************************/
if($step == 1) {
?>
<h1>Global Ban Full Installation</h1>
<form action="install.php" method="post">
  <table>
    <tr>
      <td>Database Host:</td>
      <td><input type="text" id="dbhost" name="dbhost" value="localhost"></td>
      <td>(Normally localhost unless your database is external)</td>
    </tr>
    <tr>
      <td>Database Username:</td>
      <td><input type="text" id="dbuser" name="dbuser"></td>
      <td></td>
    </tr>
    <tr>
      <td>Database Password:</td>
      <td><input type="password" id="dbpass" name="dbpass"></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td><input type="submit" value="Continue"></td>
      <td></td>
    </tr>
  </table>
  <input type="hidden" id="step" name="step" value="2"/>
</form>
<?php
}
/*************************************************
 * END STEP 1
 *************************************************/
?>




<?php
/*************************************************
 * STEP 2 - THE SECOND STEP
 * SELECT THE DATABASE TO USE
 *************************************************/
if($step == 2) {
?>
<script language="javascript">
function removeCharacters(element) {

  searchValue = element.value.replace(/\D/g,"");
  element.value = searchValue;
}

var emailCount = 2;
function addEmailRow(){
    var tbody = document.getElementById("generalSettings").getElementsByTagName("TBODY")[0];
    var row = document.createElement("TR");
    var td1 = document.createElement("TD");
    var td2 = document.createElement("TD");
    var td3 = document.createElement("TD");
    
    var emailInput = document.createElement("input");
    emailInput.setAttribute("type", "text");
    emailInput.setAttribute("size", "40");
    emailInput.setAttribute("maxLength", "255");
    emailInput.setAttribute("name", "email"+emailCount);
    
    td2.appendChild(emailInput);
    
    row.appendChild(td1);
    row.appendChild(td2);
    row.appendChild(td3);
    tbody.appendChild(row);
    emailCount++;
    document.getElementById("emailCount").value = emailCount;
  }
</script>
<h1>Global Ban Full Installation</h1>
<p>
  <ul>
    <li>Select "New Database" if you want this script to create a new database for GlobalBan. (The username you entered before MUST have database create privileges!)</li>
    <li>Select "Existing Database" if you want to use an existing database.  For SMF integration, you will want to select your SMF database.</li>
  </ul>
</p>
<form action="install.php" method="post" id="step0">
  <table>
    <tr>
      <td colspan="2">
        <input type="radio" name="newOrExisting" value="New" checked onclick="document.getElementById('dbInputName').style.display='';document.getElementById('dbSelectName').style.display='none';">New Database
        <input type="radio" name="newOrExisting" value="Existing" onclick="document.getElementById('dbSelectName').style.display='';document.getElementById('dbInputName').style.display='none';">Existing Database
      </td>
      <td></td>
    </tr>
    <tr>
      <td>Database Name:</td>
      <td id="dbInputName"><input type="text" id="dbnameinput" name="dbnameinput"" value="global_ban"></td>
      <td id="dbSelectName" style="display:none;">
        <select id="dbnameselect" name="dbnameselect">
          <?php
            $dbs = $installAndUpgrade->getListOfDatabases();
            for($i=0; $i<count($dbs); $i++) {
              echo "<option>".$dbs[$i]."</option>";
            }
          ?>
        </select>
      </td>
      <td></td>
    </tr>
    </table>
    <h3>Configuration Values</h3>
    <input type="hidden" id="emailCount" name="emailCount" value="1"/>
    <table id="generalSettings">
    <tr>
      <th colspan="3" align="left"><b>Global Ban Site Settings</b></td>
    </tr>
    <tr>
      <td>Bans Per Page:</td>
      <td><input type="text" name="bansPerPage" value="100" size="10" maxlength="5" onkeyup="removeCharacters(this)"/></td>
      <td>(Number of bans to display on ban list page for each page (-1 show all))</td>
    </tr>
    <tr>
      <td>Number of Page Links:</td>
      <td><input type="text" name="numPageLinks" value="2" size="5" maxlength="2" onkeyup="removeCharacters(this)"/></td>
      <td>(Number of links to show before and after selected page (IE: set at 2 you would see 1 2 ... 10 11 [12] 13 14 ... 23 24))</td>
    </tr>
    <tr>
      <td>Demo Directory:</td>
      <td><input type="text" name="demoDir" value="demos" size="40" maxlength="40"/></td>
      <td>(Folder to save demos to (folder must be relative to banned dir)</td>
    </tr>
    <tr>
      <td>Demo Size Limit(MB):</td>
      <td><input type="text" name="demoSizeLimit" value="30" size="10" maxlength="5" onkeyup="removeCharacters(this)"/></td>
      <td></td>
    </tr>
    <tr>
      <td>Site Name:</td>
      <td><input type="text" name="siteName" value="GlobalBan" size="40" maxlength="255"/></td>
      <td></td>
    </tr>
    <tr>
      <td>Site URL:</td>
      <td><input type="text" name="siteURL" value="http://www.yoursite.com" size="40" maxlength="255"/></td>
      <td>(Your clan/server's home page)</td>
    </tr>
    <tr>
      <td>Logo:</td>
      <td><input type="text" name="logo" value="logo.png" size="40" maxlength="100"/></td>
      <td>(Enter the name of the image file you placed in the images folder)</td>
    </tr>
    <tr>
      <td>Create User Code:</td>
      <td><input type="text" name="createUserCode" value="" size="20" maxlength="30"/></td>
      <td>(Code that new users will need to enter to create an account; not needed for SMF)</td>
    </tr>
    <tr>
      <td>Create Super User Code:</td>
      <td><input type="text" name="createSuperUserCode" value="" size="20" maxlength="30"/></td>
      <td>(Code that new super users will need to enter to create an account; not needed for SMF)</td>
    </tr>
    <tr>
      <td>Send Emails on Ban:</td>
      <td><select name="sendEmailsOnBan"><option value="true">Yes</option><option value="false">No</option></select></td>
      <td>(Send an email notification to ban managers when a new ban is added)</td>
    </tr>
    <tr>
      <td>Send Emails on Demo Add:</td>
      <td><select name="sendEmailsDemo"><option value="true">Yes</option><option value="false" selected>No</option></select></td>
      <td>(Send an email notification to ban managers when a new demo is added)</td>
    </tr>
    <tr>
      <td>Email Address of Sender:</td>
      <td><input type="text" name="senderEmail" value="bans@yoursite.com" size="40" maxlength="255"/></td>
      <td></td>
    </tr>
    <tr>
      <td>Email Addresses to Recieve Ban and Demo Notices:</td>
      <td><input type="text" name="email1" value="email@somewhere.com" size="40" maxlength="255"/></td>
      <td><input type="button" value="Add another email" onclick="addEmailRow(2)"/></td>
    </tr>
    </table>
    
    <br/>
    
    <table>
    <tr>
      <th colspan="3" align="left"><b>Forum Settings</b></td>
    </tr>
    <tr>
      <td>Enable Forum Link:</td>
      <td><select name="enableForumLink"><option value="true">Yes</option><option value="false">No</option></select></td>
      <td></td>
    </tr>
    <tr>
      <td>Forum URL:</td>
      <td><input type="text" name="forumURL" value="http://www.yoursite.com/Forums" size="40" maxlength="255"/></td>
      <td></td>
    </tr>
    </table>
    
    <br/>
    
    <table>
    <tr>
      <th colspan="3" align="left"><b>Ban Settings</b></td>
    </tr>
    <tr>
      <td>Ban Message:</td>
      <td><input type="text" name="banMessage" value="You are banned. Appeal at yourdomain.com" size="60" maxlength="255"/></td>
      <td>(Message to display to those banned)</td>
    </tr>
    <tr>
      <td>Ban Appeal Site:</td>
      <td><input type="text" name="banAppealSite" value="http://www.yourdomain.com" size="40" maxlength="255"/></td>
      <td>(Site where banned users should appeal a ban)</td>
    </tr>
    <tr>
      <td>Days to keep a pending banned:</td>
      <td><input type="text" name="daysBanPending" value="5" size="10" maxlength="5" onkeyup="removeCharacters(this)"/></td>
      <td>(Number of days to keep someone with a "pending" ban off the server (0 to let the person come back after being "banned"); this only affects "members" who do bans longer than 1 day)</td>
    </tr>
    <tr>
      <td>Allow Admins to be Banned:</td>
      <td><select name="allowAdminBan"><option value="true">Yes</option><option value="false" selected>No</option></select></td>
      <td>(Can admins be banned by other admins?)</td>
    </tr>
    <tr>
      <td>Hash key in Eventscript Config:</td>
      <td><input type="text" name="hash" value="" size="40" maxlength="255"/></td>
      <td>(This MUST match the hash you place in your eventscripts GlobalBan.cfg file)</td>
    </tr>
    </table>

    <br/>

    <table>
    <tr>
      <th colspan="3" align="left"><b>SMF Integration</b></td>
    </tr>
    <tr>
      <td>SMF Integration:</td>
      <td><select name="smfIntegration"><option value="true">Yes</option><option value="false" selected>No</option></select></td>
      <td></td>
    </tr>
    <tr>
      <td>SMF Member Group:</td>
      <td><input type="text" name="smfMemberGroup" value="0" size="10" maxlength="5" onkeyup="removeCharacters(this)"/></td>
      <td>(The group id of the SMF group that will contain the "members")</td>
    </tr>
    <tr>
      <td>SMF Admin Group:</td>
      <td><input type="text" name="smfAdminGroup" value="0" size="10" maxlength="5" onkeyup="removeCharacters(this)"/></td>
      <td>(The group id of the SMF group that will contain the "admins")</td>
    </tr>
    <tr>
      <td>SMF Ban Manger Group:</td>
      <td><input type="text" name="smfBanManagerGroup" value="0" size="10" maxlength="5" onkeyup="removeCharacters(this)"/></td>
      <td>(The group id of the SMF group that will contain the "ban managers")</td>
    </tr>
    <tr>
      <td>SMF Full Power Group:</td>
      <td><input type="text" name="smfFullPowerGroup" value="0" size="10" maxlength="5" onkeyup="removeCharacters(this)"/></td>
      <td>(The group id of the SMF group that will contain the "full power admins")</td>
    </tr>
  </table>
  <input type="hidden" id="step" name="step" value="3"/>
  <input type="submit" value="Install GlobalBan">
</form>
<?php
}
/*************************************************
 * END STEP 2
 *************************************************/
?>


<?php
/*************************************************
 * STEP 3 - THE LAST PAGE
 * ALL DATABASE TABLES CREATED AND CONFIG SET
 *************************************************/
if($step == 3) {
?>
<script type="text/javascript">
window.location = "installComplete.php"
</script>
<?php
}
/*************************************************
 * END STEP 3
 *************************************************/
?>
